<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2019/2/20
 * Time: 17:22
 */

namespace app\common\model;


use think\Cache;

/**
 * 用户星盘相关配置模型
 * Class AstroSettingUser
 * @package app\common\model
 */
class AstroSettingUser extends Base
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_astro_setting_user';

    const CACHE_KEY = 'astro:setting:';// . $chart . ':' . $uid . ':' . $tid
    const CACHE_TIME = 86400 * 2;

    const CACHE_KEY_OLD = 'user_astro_setting_';// . $uid . '-' . $chart .  '-' . $tid
    const TABLE_NAME_OLD = 'wechat_backup_07_18_14_43_00.app_astro_setting';

    const CACHE_KEY_OLD_DIVINATION = 'astro_set_';// . $uid . '_' . $tid
    const TABLE_NAME_OLD_DIVINATION = 'wechat_backup_07_18_14_43_00.app_astro_setting_divination';

    /**
     * 从原来的表中读取用户配置数据
     * @param array $map
     * @return bool|false|mixed|string
     */
    private function getUserSettingFromOldtable($map = [])
    {
        $result = false;

        // 先从缓存获取
        if ($this->cache_on >= 1)
        {
            // 提问盘配置缓存在另外的key中
            if ($map['chart'] === 'divination')
            {
                $result = Cache::get(self::CACHE_KEY_OLD_DIVINATION . $map['uid'] . '-' . $map['tid']);
            } else
            {
                $result = Cache::get(self::CACHE_KEY_OLD . $map['uid'] . '-' . $map['chart'] . '-' . $map['tid']);
            }
        }
        // 读取配置文件
        $astrosetConfig = config('astroset');

        if ($result === false)
        {
            $where = ['uid' => $map['uid'], 'tid' => $map['tid']];
            try
            {
                // 提问盘配置在另外的表中
                if ($map['chart'] === 'divination')
                {
                    $result = $this->table(self::TABLE_NAME_OLD_DIVINATION)
                        ->field('tid,uid,asp_orb_all,asps_display,planets_display,planet_orb_all,h_sys')
                        ->where($where)
                        ->find();

                    if (!empty($result) && $result !== null)
                    {
                        $result['asp_orb_all'] = json_decode($result['asp_orb_all'], true);
                        $result['asps_display'] = json_decode($result['asps_display'], true);
                        $result['planet_orb_all'] = json_decode($result['planet_orb_all'], true);
                    }
                }// 由于有新增新的星盘，所以旧表中没有该字段需要过滤
                elseif (in_array($map['chart'], ['now', 'natal', 'transits', 'thirdprogressedvsnatal', 'thirdprogressed', 'progressionvsnatal', 'progressions', 'solar', 'solar_return', 'lunar_return', 'firdaria', 'profection', 'synastry', 'composite', 'composite_thirdprogressed', 'composite_progressions', 'davison', 'marks']))
                {
                    $result = $this->table(self::TABLE_NAME_OLD)
                        ->where($where)
                        ->value($map['chart']);
                } else
                {
                    $result = '';
                }
                $result = json_decode($result, true);

                $default = true;
                $temp = [];

                if(!empty($result))
                {
                    foreach ($astrosetConfig['setting' . $map['tid']][$map['chart']] as $chart => $v)
                    {
                        // 过滤多余的数据
                        if (isset($result[$chart]))
                        {
                            $temp[$chart] = $v;
                            if ($default === true && $result[$chart] != $v)
                            {
                                $default = false;
                            }
                        }
                    }
                }

                // 用户数据与默认配置一致
                if ($default === true)
                {
                    $result = 'default';
                }// 用户自定义配置
                else
                {
                    $result = json_encode($temp);
                }

                // 则添加到新表中
                $data = ['uid' => $map['uid'], 'tid' => $map['tid'], 'chart' => $map['chart'], 'value' => $result, 'create_time' => time()];

                if ($this->save($data) && $this->cache_on >= 1)
                {
                    Cache::set(self::CACHE_KEY . $map['chart'] . ':' . $map['uid'] . ':' . $map['tid'], $result, self::CACHE_TIME);
                }
            }
            catch (\Exception $e)
            {
                \think\Log::write('旧星盘配置导入新表失败：' . $e->getMessage(), 'error');
                $result = false;
            }
        }

        return $result;
    }

    /**
     * 获取用户自定义星盘设置
     * @param array $map
     *  tid int 配置方案 1=>现代 2=>古典 3=>特殊
     *  uid int 用户id
     *  chart string 星盘名称 如：now 表示天象盘
     * @return array|bool
     */
    public function getUserSettingByTid($map = [])
    {
        $tid = (int)($map['tid']);
        $uid = (int)($map['uid']);
        $chart = $map['chart'];
        // 初始化
        $setting = false;
        // 从新的缓存获取数据
        if ($this->cache_on >= 1)
        {
            $setting = Cache::get(self::CACHE_KEY . $chart . ':' . $uid . ':' . $tid);
        }
        // 缓存没有数据
        if ($setting === false)
        {
            $where = ['uid' => $uid, 'tid' => $tid, 'chart' => $chart];
            // 从新的表中获取数据
            try
            {
                $setting = $this->where($where)->value('value');

                if ($setting !== null && $setting !== 'default')
                {
                    $settingDecode = json_decode($setting, true);
                    // 重新json格式化，使数据格式统一
                    $setting = json_encode($settingDecode, true);

                    if ($this->cache_on >= 1)
                    {
                        Cache::set(self::CACHE_KEY . $chart . ':' . $uid . ':' . $tid, $setting, self::CACHE_TIME);
                    }

                    $setting = $settingDecode;
                } elseif ($setting === null)
                {
                    $setting = false;
                }
            }
            catch (\Exception $e)
            {
                $setting = false;
            }
        }
        // 若无，先从旧的表中获取数据
        if ($setting === false)
        {
            $setting = $this->getUserSettingFromOldtable($map);
            // 用户使用默认配置
            if ($setting === 'default' || $setting === false)
            {
                // 读取配置文件
                $astrosetConfig = config('astroset');

                $setting = $astrosetConfig['setting' . $map['tid']][$map['chart']];
                $setting['is_default'] = true;
            } else
            {
                if (!is_array($setting)) $setting = json_decode($setting, true);
                if (isset($setting[$chart]) && is_string($setting[$chart])) $setting = json_decode($setting[$chart], true);
                $setting['is_default'] = false;


//                \think\Log::write(var_export($setting,true),'log',true);
            }
        }

        // 若缓存中存储的数据为 default 字符串，则表示用户使用默认配置.
        if ($setting === 'default')
        {
            $setting = config('astroset.setting' . $tid)[$chart];

            $setting['is_default'] = true;
        }// 用户自定义配置
        else
        {
            if (!is_array($setting))
            {
                $setting = json_decode($setting, true);
            }
            $setting['is_default'] = false;
        }
        return $setting;
    }

    /**
     * 更新用户星盘配置
     * @param array $map
     * @return AstroSettingUser|bool
     */
    public function updateUserSetting($map = [])
    {
        try
        {
            // 将客户端传来的数据重新json格式化，保证入库格式统一
            $value = json_encode(json_decode($map['chart_value'], true), true);

            $where = [
                'uid' => (int)($map['uid']),
                'tid' => (int)($map['tid']),
                'chart' => $map['chart'],
            ];
            // 更新数据库数据
            $result = $this->where($where)->update(['value' => $value, 'update_time' => time()]);

            // 更新完成 更新缓存
            if ($result !== false && $this->cache_on >= 1)
            {
                Cache::set(self::CACHE_KEY . $map['chart'] . ':' . $map['uid'] . ':' . $map['tid'], $value, self::CACHE_TIME);
            }
            $result = true;
        }
        catch (\Exception $e)
        {
            \think\Log::write($e->getMessage(), 'log', true);
            $result = false;
        }

        return $result;
    }

    /**
     * 星盘配置还原
     * @param array $map
     * @return bool
     */
    public function restoreUserSetting($map = [])
    {
        $where = ['uid' => (int)($map['uid']), 'tid' => (int)($map['tid']), 'chart' => $map['chart']];

        $value = 'default';

        try
        {
            $this->where($where)->update(['value' => $value]);
            // 更新完成 更新缓存
            if ($this->cache_on >= 1)
            {
                Cache::set(self::CACHE_KEY . $map['chart'] . ':' . $map['uid'] . ':' . $map['tid'], $value, self::CACHE_TIME);
            }
        }
        catch (\Exception $e)
        {
            $this->error = $e->getMessage();

            return false;
        }
        return true;
    }
}
